package com.kevin.pay.controller;

import com.kevin.pay.config.WeChatConfig;
import com.kevin.pay.domain.JsonData;
import com.kevin.pay.domain.User;
import com.kevin.pay.domain.Video;
import com.kevin.pay.domain.VideoOrder;
import com.kevin.pay.service.UserService;
import com.kevin.pay.service.VideoOrderService;
import com.kevin.pay.utils.JwtUtils;
import com.kevin.pay.utils.WxPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;

@Controller
@RequestMapping("/api/v1/wechat")
public class WechatController {

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private VideoOrderService videoOrderService;

    /**
     * 拼装微信扫一扫登录url
     * @return
     */
    @GetMapping("login_url")
    @ResponseBody
    public JsonData loginUrl(@RequestParam(value = "access_page") String accessPage) throws UnsupportedEncodingException {

        String redirctUrl=weChatConfig.getOpenRedirectUrl();

        String callbackUrl= URLEncoder.encode(redirctUrl,"GBK");

        String qrcodeUrl=String.format(WeChatConfig.getOpenQrcodeUrl(),weChatConfig.getOpenAppid(),callbackUrl,accessPage);

        return JsonData.buildSuccess(qrcodeUrl);
    }

    @GetMapping("/user/callback")
    public void wechatUserCallback(@RequestParam(value = "code") String code,
                                   String state, HttpServletResponse response) throws IOException {

        User user=userService.saveWeChatUser(code);

        if(user!=null){
            //生成jwt
            String token= JwtUtils.geneJsonWebToken(user);
            // state 当前用户的页面地址，需要拼接 http://  这样才不会站内跳转
            response.sendRedirect(state+"?token="+token+"&head_img="+user.getHeadImg()+"&name="+URLEncoder.encode(user.getName(),"UTF-8"));
        }
    }

    @RequestMapping("/order/callback")
    public void orderCallback(HttpServletRequest request,HttpServletResponse response) throws Exception {
        InputStream inputStream = request.getInputStream();

        //BufferReader baoz包装设计类，性能更好
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();
        inputStream.close();
        Map<String, String> callbackMap = WxPayUtil.xmlToMap(sb.toString());
        System.out.println(callbackMap.toString());

        SortedMap<String,String> sortedMap=WxPayUtil.getSortedMap(callbackMap);

        if (WxPayUtil.isCorrectSign(sortedMap,weChatConfig.getKey())){

            if ("SUCCESS".equals(sortedMap.get("result_code"))){
                String outTradeNo=sortedMap.get("out_trade_no");
                VideoOrder videoOrder=videoOrderService.findByOutTradeNo(outTradeNo);
                if (videoOrder!=null&&videoOrder.getState()==0){
                    VideoOrder order=new VideoOrder();
                    order.setOpenid(sortedMap.get("openid"));
                    order.setOutTradeNo(outTradeNo);
                    order.setNotifyTime(new Date());
                    order.setState(1);
                    int rows=videoOrderService.updateVideoOrderByOutTradeNo(order);
                    if (rows==1){
                        response.setContentType("text/html");
                        response.getWriter().println("success");
                        return;
                    }
                }

            }
        }
        response.setContentType("text/html");
        response.getWriter().println("fail");
    }


}
